package cn.yuanqiao.web.controller.system;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.yuanqiao.common.constant.SysContants;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.core.domain.TreeSelect;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.service.SysPermissionService;
import cn.yuanqiao.feignService.ApiSystemService;
import cn.yuanqiao.feignService.impl.ApiSystemServiceImpl;
import cn.yuanqiao.system.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import cn.yuanqiao.common.annotation.Log;
import cn.yuanqiao.common.core.controller.BaseController;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.core.domain.entity.SysDept;
import cn.yuanqiao.common.core.domain.entity.SysRole;
import cn.yuanqiao.common.core.domain.entity.SysUser;
import cn.yuanqiao.common.core.page.TableDataInfo;
import cn.yuanqiao.common.enums.BusinessType;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.poi.ExcelUtil;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ApiSystemServiceImpl apiSystemService;

    @Value("${encryption}")
    private String encryption;

    /**
     * 获取用户列表
     */
    //@PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    //@PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport,Long deptId) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName,deptId);
        return success(message);
    }



    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    //@PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String username = SecurityUtils.getUsername();
        String tenantCode = SecurityUtils.getTenantCode();
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId))
        {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId).stream()
                    .map(String::valueOf)
                    .collect(Collectors.toList()));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()).stream()
                    .map(String::valueOf)
                    .collect(Collectors.toList()));
        }
        return ajax;
    }

    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        String userType = SecurityUtils.getUserType();
        logger.info("登录用户类型：：：" + userType);
        AjaxResult ajax = AjaxResult.success();
        if (SysContants.MANAGEDEPTFLAG.equals(userType)) {
            SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
            //System.out.println(sysUser);
            R<String> menuPermission = apiSystemService.getMenuPermission(SysContants.MANAGEROLEFLAG);
            String permissionStr = menuPermission.getData();
            Set<String> permissions = new HashSet<>();
            if(StringUtils.isNotEmpty(permissionStr)){
                String[] permissionStrArr = permissionStr.split(",");
                List<String> strs = Arrays.asList(permissionStrArr);
                permissions = new HashSet<>(strs);
            }
            Set<String> roles = new HashSet<>();
            roles.add(SysContants.MANAGEROLEFLAG);
            ajax.put("user", sysUser);
            ajax.put("roles", roles);
            ajax.put("permissions", permissions);
            /*R<LoginUser> userInfo = remoteManageService.getUserInfo(SecurityUtils.getUsername(), SecurityConstants.INNER);
            LoginUser loginUser = userInfo.getData();
            ajax.put("user", loginUser.getUser());
            ajax.put("roles", loginUser.getRoles());
            ajax.put("permissions", loginUser.getPermissions());*/
            //SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();

        } else {
            SysUser user = userService.selectUserById(SecurityUtils.getUserId());
            // 角色集合
            Set<String> roles = permissionService.getRolePermission(user);
            // 权限集合
            Set<String> permissions = permissionService.getMenuPermission(user);
            ajax.put("user", user);
            ajax.put("roles", roles);
            ajax.put("permissions", permissions);
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    //@PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword(),encryption));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    //@PreAuthorize("@ss.hasAnyPermi('system:user:edit,system:user:authRole')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    //@PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword(),encryption));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    @PutMapping("/editSys")
    public AjaxResult editSys(@RequestBody SysUser user) {
        user.setUpdateBy(SecurityUtils.getUsername());
        String result=userService.editSys(user);
        if ("success".equals(result)){
            return toAjax(1);
        }else if("fail".equals(result)){
            return toAjax(0);
        }else{
            return error(result);
        }
    }

    /**
     * 状态修改
     */
    //@PreAuthorize("@ss.hasPermi('system:user:authRole')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:authRole')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }

    /**
     * 获取部门树列表
     */
    @GetMapping("/deptTreeNoDateScope")
    public AjaxResult deptTreeNoDateScope(SysDept dept) {
        dept.setTenantCode(SecurityUtils.getTenantCode());
        List<TreeSelect> treeSelects = deptService.deptTreeNoDateScope(dept);
        return success(treeSelects);
    }

    /**
     * 获取部门树列表
     */
    @GetMapping("/deptUserTree")
    public AjaxResult deptUserTree(SysDept dept) {
        dept.setTenantCode(SecurityUtils.getTenantCode());
        List<TreeSelect> treeSelects = deptService.selectDeptUserTreeList(dept);
        return success(treeSelects);
    }

    /**
     * 获取部门树列表
     */
    @GetMapping("/deptUserTreeNoDateScope")
    public AjaxResult deptUserTreeNoDateScope(SysDept dept) {
        dept.setTenantCode(SecurityUtils.getTenantCode());
        List<TreeSelect> treeSelects = deptService.selectDeptUserTreeListNoDateScope(dept);
        return success(treeSelects);
    }

    @GetMapping("/roleUserTreeNoDateScope")
    public AjaxResult roleUserTreeNoDateScope(SysRole role) throws ServiceException {
        role.setTenantCode(SecurityUtils.getTenantCode());
        String roleKey = sysConfigService.selectConfigByKey("NEXT_ASSIGNEE_ROLE_KEY");
        if(StringUtils.isEmpty(roleKey)||"null".equals(roleKey)){
            //throw new ServiceException("系统参数错误NEXT_ASSIGNEE_ROLE_KEY未找到配置！");
            return null;
        }
        role.setRoleKey(roleKey);
        List<TreeSelect> treeSelects = userService.roleUserTreeNoDateScope(role);
        return success(treeSelects);
    }

    /**
     * gw  zt 根据部门id查询本部门及以下部门的人员
     */
    @GetMapping("/findByDeptUserTree")
    public AjaxResult findByDeptAndUserAndTree(String deptId) {
        SysDept dept = new SysDept();
        dept.setTenantCode(SecurityUtils.getTenantCode());
        List<TreeSelect> treeSelects = deptService.selectDeptUserTreeList(dept);
        return success(getDept(deptId, treeSelects.get(0)));
    }

    private List<TreeSelect> getDept(String deptId, TreeSelect children) {
        if (children == null) {
            return null;
        }
        if (children.getId().toString().equals(deptId)) {
            List<TreeSelect> list = new ArrayList<>();
            list.add(children);
            return list;
        }
        for (TreeSelect child : children.getChildren()) {
            List<TreeSelect> dept = getDept(deptId, child);
            if (CollectionUtils.isNotEmpty(dept)) {
                return dept;
            }
        }
        return null;
    }
    @GetMapping("/syslist")
    public List<SysUser> list(@RequestParam("tenantCode") String tenantCode) {
        SysUser sysUser = new SysUser();
        sysUser.setTenantCode(tenantCode);
        Map<String, Object> params = sysUser.getParams();
        StringBuffer sb = new StringBuffer();
        sb.append("'").append(tenantCode + "_" + SysContants.SYSADMINFLAG).append("',")
                .append("'").append(tenantCode + "_" + SysContants.SYSSSOFLAG).append("',")
                .append("'").append(tenantCode + "_" + SysContants.SYSAUDITORFLAG).append("',");
        sb.deleteCharAt(sb.length() - 1);
        params.put("roleKey", sb.toString());
        List<SysUser> list = userService.selectSysList(sysUser);
        for (int i = 0; i < list.size(); i++) {
            SysUser user = list.get(i);
            List<SysRole> roles = user.getRoles();
            user.setRoleName(roles.get(0).getRoleName());
            user.setRoles(null);
        }
        return list;
    }

}
